package me.zhengjie.modules.bailian.util;


// 示例代码仅供参考，请勿在生产环境中直接使用

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * UploadFile 2025/3/19 17:30
 *
 * @author Yaco
 * @version 1.0.0
 */
@Slf4j
public class UploadFile {

    public static boolean uploadFile(String preSignedUrl, String filePath, String method, String headersXBailianExtra, String contentType) {
        HttpURLConnection connection = null;
        try {
            // 创建URL对象
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 允许向connection输出，因为这个连接是用于上传文档的
            connection.setDoOutput(true);

            // 设置请求方法用于文档上传，需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
//            connection.setRequestMethod("PUT");
//            connection.setRequestProperty("X-bailian-extra", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值");
//            connection.setRequestProperty("Content-Type", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值");

            connection.setRequestMethod(method);
            connection.setRequestProperty("X-bailian-extra", headersXBailianExtra);
            connection.setRequestProperty("Content-Type", contentType);

            // 读取文档并通过连接上传
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 FileInputStream fileInputStream = new FileInputStream(filePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // 检查响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 文档上传成功处理
                log.info("File uploaded successfully.");
                return true;
            } else {
                // 文档上传失败处理
                log.info("Failed to upload the file. ResponseCode: " + responseCode);
            }
        } catch (Exception e) {
            log.error(" ### UploadFile Exception", e);

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return false;
    }

    public static void uploadFileLink(String preSignedUrl, String sourceUrlString) {
        HttpURLConnection connection = null;
        try {
            // 创建URL对象
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法用于文档上传，需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
            connection.setRequestMethod("PUT");

            // 允许向connection输出，因为这个连接是用于上传文档的
            connection.setDoOutput(true);

            connection.setRequestProperty("X-bailian-extra", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值");
            connection.setRequestProperty("Content-Type", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值");

            URL sourceUrl = new URL(sourceUrlString);
            HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();

            // 设置访问OSS的请求方法为GET
            sourceConnection.setRequestMethod("GET");
            // 获取响应码，200表示请求成功
            int sourceFileResponseCode = sourceConnection.getResponseCode();

            // 从OSS读取文档并通过连接上传
            if (sourceFileResponseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to get source file.");
            }
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) {
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = in.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }

                outStream.flush();
            }

            // 检查响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 文档上传成功
                System.out.println("File uploaded successfully.");
            } else {
                // 文档上传失败
                System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) {

//        String preSignedUrlOrHttpUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";

        // 文档来源可以是本地，上传本地文档至百炼临时存储
//        String filePath = "请替换为您需要上传文档的实际本地路径";
//        uploadFile(preSignedUrlOrHttpUrl, filePath);

        // 文档来源还可以是OSS
        // String filePath = "请替换为您需要上传文档的实际OSS可公网访问地址";
        // uploadFileLink(preSignedUrlOrHttpUrl, filePath);
    }
}
